<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="对应课程" prop="courseId">
        <el-popover ref="courseListPopover" placement="bottom-start" trigger="click" v-model="popoverVisible">
          <el-tree
            :data="courseList"
            :props="courseTreeProps"
            node-key="courseId"
            ref="courseListTree"
            @current-change="courseTreeCurrentChangeHandle"
            :default-expand-all="true"
            :highlight-current="true"
            :expand-on-click-node="false"
          ></el-tree>
        </el-popover>
        <el-input
          v-model="parentName"
          v-popover:courseListPopover
          :readonly="true"
          placeholder="点击选择上级菜单"
          class="menu-list__input"
        ></el-input>
      </el-form-item>
      <el-form-item label="缩略图" prop="img">
        <el-upload
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="视频地址" prop="videoUrl">
        <!-- <el-input v-model="dataForm.videoUrl" placeholder="视频地址"></el-input> -->
        <el-upload
          class="upload-demo"
          :action="url"
          :before-upload="beforeAvatarUploadImg"
          :before-remove="beforeRemove"
          :on-success="uploadSuccess"
          :limit="1"
          :on-exceed="handleExceed"
          multiple
          :file-list="fileList"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="dataForm.remark"></el-input>
      </el-form-item>
      <el-form-item label="排序号">
        <el-input-number :min="0" v-model="dataForm.orderNum"></el-input-number>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from "@/utils";
export default {
  data() {
    return {
      popoverVisible: false,
      url: "",
      imageUrl: "",
      fileList: [],
      fileUrlList: [],
      parentName: "",
      courseList: [],
      courseTreeProps: "",
      visible: false,
      dataForm: {
        courseVideoId: 0,
        courseId: "",
        videoUrl: "",
        img: "",
        remark: "",
        orderNum: null
      },
      dataRule: { //parentName img videoUrl
        courseId: [
          { required: true, message: '对应课程不能为空', trigger: 'change' }
        ],
        img: [
          { required: true, message: "缩略图不能为空", trigger: "blur" }
        ],
        videoUrl: [
          { required: true, message: "视频地址不能为空", trigger: "blur" }
        ]
      },
      courseTreeProps: {
        label: "courseTitle",
        children: "children"
      }
    };
  },
  methods: {
    init(id) {
      this.url = this.$http.adornUrl(
        `/sys/oss/upload?token=${this.$cookie.get("token")}`
      );

      this.dataForm.courseVideoId = id || 0;
      this.visible = true;
    
      this.imageUrl = "";

      (this.fileList = []), (this.fileUrlList = []), (this.parentName = "");

      this.$http({
        url: this.$http.adornUrl("/admin/course/stu/courseList"),
        method: "get",
        params: this.$http.adornParams()
      })
        .then(({ data }) => {
          this.courseList = treeDataTranslate(data.list, "courseId", "fId");
        })
        
      this.$nextTick(() => {

        this.$refs["dataForm"].resetFields();

        if (this.dataForm.courseVideoId) {
          this.$http({
            url: this.$http.adornUrl(
              `/admin/coursevideo/info/${this.dataForm.courseVideoId}`
            ),
            method: "get",
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.courseId = data.courseVideo.courseId;
              let URLSTR = JSON.parse(data.courseVideo.videoUrl);
              this.fileList.push({ name: URLSTR[0], url: URLSTR[0] });
              this.fileUrlList.push(URLSTR[0]);
              this.imageUrl = data.courseVideo.img;
              this.courseListTreeSetCurrentNode();
              this.dataForm.remark= data.courseVideo.remark
              this.dataForm.orderNum= data.courseVideo.orderNum
              this.dataForm.img = data.courseVideo.img
              this.dataForm.videoUrl = data.courseVideo.videoUrl
            }
          });
        }else{
           this.dataForm.remark= ''
              this.dataForm.orderNum= null
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      console.log(this.dataForm)
      this.$refs["dataForm"].validate(valid => { 
        if (valid) {
          this.dataForm.videoUrl = JSON.stringify( this.dataForm.videoUrl)
          this.$http({
            url: this.$http.adornUrl(
              `/admin/coursevideo/${
                !this.dataForm.courseVideoId ? "save" : "update"
              }`
            ),
            method: "post",
            data: this.$http.adornData({
              courseVideoId: this.dataForm.courseVideoId || undefined,
              courseId: this.dataForm.courseId,
              videoUrl: JSON.stringify(this.fileUrlList), //this.dataForm.videoUrl
              img: this.dataForm.img,
              remark: this.dataForm.remark,
              orderNum: this.dataForm.orderNum
              ///...this.dataForm
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 菜单树选中
    courseTreeCurrentChangeHandle(data, node) {
      if (data._level !== 3) {
        this.$message.warning("请选择对应目录");
        return false;
      }
      this.dataForm.courseId = data.courseId;
      this.parentName = data.courseTitle;
      this.popoverVisible = !this.popoverVisible
    },
    // 菜单树设置当前选中节点
    courseListTreeSetCurrentNode() {
      //debugger
      this.$refs.courseListTree.setCurrentKey(this.dataForm.courseId);
      this.parentName = (this.$refs.courseListTree.getCurrentNode() || {})[
        "courseTitle"
      ];
    },
    beforeRemove(file, fileList) {
      this.fileUrlList.splice(fileList.indexOf(file), 1);
    },
    uploadSuccess(response, file, fileList) {
      this.fileUrlList.push(response.url);
      this.dataForm.videoUrl = this.fileUrlList
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.dataForm.img = res.url;
    },
    beforeAvatarUpload(file) {
      if (
        file.type !== "image/jpg" &&
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/gif"
      ) {
        this.$message.error("只支持jpg、png、gif格式的图片！");
        return false;
      }
    },
    beforeAvatarUploadImg(file){
      if (['video/mp4', 'video/ogg', 'video/flv','video/avi','video/wmv','video/rmvb'].indexOf(file.type) == -1) {
        this.$message.error('请上传正确的视频格式');
        return false;
      }
    },

    handleExceed(files, fileList) {
      this.$message.warning(`最多上传一个视频`);
    }
  }
};
</script>
